// 测试用户关注功能的脚本
const axios = require('axios');
const fs = require('fs');
const path = require('path');

// 配置
const API_BASE_URL = 'http://localhost:3000/api/v1';
const LOGIN_USER = {
  username: 'user',
  password: '123456'
};
const TARGET_USER_ID = 2; // 要关注的目标用户ID
const TEST_RESULTS_FILE = 'test_user_follow_results.md';

let token = '';
let currentUserId = null;
let results = [];

// 日志函数
function log(message) {
  console.log(message);
  results.push(message);
}

// 登录获取token
async function login() {
  try {
    log('\n=== 开始登录 ===');
    const response = await axios.post(`${API_BASE_URL}/auth/login`, LOGIN_USER);
    
    if (response.status === 200 && response.data.success && response.data.data && response.data.data.tokens) {
      token = response.data.data.tokens.accessToken;
      currentUserId = response.data.data.user.id;
      log(`✓ 登录成功，用户ID: ${currentUserId}`);
      return true;
    } else {
      log(`✗ 登录失败: ${response.data.message || '未知错误'}`);
      log(`登录响应: ${JSON.stringify(response.data)}`);
      return false;
    }
  } catch (error) {
    log(`✗ 登录请求出错: ${error.message}`);
    return false;
  }
}

// 检查关注状态
async function checkFollowStatus() {
  try {
    log('\n=== 检查关注状态 ===');
    const response = await axios.get(
      `${API_BASE_URL}/users/follow/${TARGET_USER_ID}/check`,
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );
    
    if (response.status === 200) {
      const isFollowing = response.data.data.isFollowing;
      log(`✓ 关注状态检查成功: 当前${isFollowing ? '已关注' : '未关注'}用户 ${TARGET_USER_ID}`);
      return isFollowing;
    } else {
      log(`✗ 关注状态检查失败: ${response.data.message || '未知错误'}`);
      return null;
    }
  } catch (error) {
    log(`✗ 关注状态检查请求出错: ${error.message}`);
    return null;
  }
}

// 切换关注状态
async function toggleFollow() {
  try {
    log('\n=== 切换关注状态 ===');
    const response = await axios.post(
      `${API_BASE_URL}/users/follow/${TARGET_USER_ID}`,
      {},
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );
    
    if (response.status === 200) {
      const followed = response.data.data.followed;
      log(`✓ 切换关注状态成功: ${followed ? '已关注' : '取消关注'}用户 ${TARGET_USER_ID}`);
      return followed;
    } else {
      log(`✗ 切换关注状态失败: ${response.data.message || '未知错误'}`);
      return null;
    }
  } catch (error) {
    log(`✗ 切换关注状态请求出错: ${error.message}`);
    if (error.response) {
      // 服务器返回了错误响应
      log(`错误响应状态码: ${error.response.status}`);
      log(`错误响应数据: ${JSON.stringify(error.response.data)}`);
    } else if (error.request) {
      // 请求已发送但没有收到响应
      log(`没有收到服务器响应`);
    } else {
      // 请求配置出错
      log(`请求配置错误: ${error.message}`);
    }
    return null;
  }
}

// 获取用户关注统计
async function getFollowStats() {
  try {
    log('\n=== 获取用户关注统计 ===');
    const response = await axios.get(
      `${API_BASE_URL}/users/${currentUserId}/follow/stats`,
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );
    
    if (response.status === 200) {
      const { followingCount, followersCount } = response.data.data;
      log(`✓ 获取关注统计成功: 关注数=${followingCount}, 粉丝数=${followersCount}`);
      return { followingCount, followersCount };
    } else {
      log(`✗ 获取关注统计失败: ${response.data.message || '未知错误'}`);
      return null;
    }
  } catch (error) {
    log(`✗ 获取关注统计请求出错: ${error.message}`);
    return null;
  }
}

// 获取关注列表
async function getFollowingList() {
  try {
    log('\n=== 获取关注列表 ===');
    const response = await axios.get(
      `${API_BASE_URL}/users/${currentUserId}/following?page=1&limit=10`,
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );
    
    if (response.status === 200) {
      const following = response.data.data.following;
      log(`✓ 获取关注列表成功: 共${following.length}个关注`);
      following.forEach(item => {
        log(`  - 用户ID: ${item.userId}, 用户名: ${item.user.username}, 关注时间: ${item.followedAt}`);
      });
      return following;
    } else {
      log(`✗ 获取关注列表失败: ${response.data.message || '未知错误'}`);
      return null;
    }
  } catch (error) {
    log(`✗ 获取关注列表请求出错: ${error.message}`);
    return null;
  }
}

// 批量检查关注状态
async function batchCheckFollowStatus() {
  try {
    log('\n=== 批量检查关注状态 ===');
    const userIds = [1, 2, 3]; // 测试多个用户ID
    const response = await axios.post(
      `${API_BASE_URL}/users/follow/batch-check`,
      { userIds },
      {
        headers: { Authorization: `Bearer ${token}` }
      }
    );
    
    if (response.status === 200) {
      const followStatus = response.data.data;
      log(`✓ 批量检查关注状态成功`);
      followStatus.forEach(item => {
        log(`  - 用户ID: ${item.userId}, 关注状态: ${item.isFollowing ? '已关注' : '未关注'}`);
      });
      return followStatus;
    } else {
      log(`✗ 批量检查关注状态失败: ${response.data.message || '未知错误'}`);
      return null;
    }
  } catch (error) {
    log(`✗ 批量检查关注状态请求出错: ${error.message}`);
    return null;
  }
}

// 保存测试结果到文件
function saveResults() {
  const timestamp = new Date().toISOString();
  const content = `# 用户关注功能测试结果

测试时间: ${timestamp}

## 测试步骤和结果

${results.join('\n')}

## 总结
${results.filter(r => r.startsWith('✓')).length} 项测试成功，${results.filter(r => r.startsWith('✗')).length} 项测试失败
`;
  
  fs.writeFileSync(TEST_RESULTS_FILE, content, 'utf8');
  log(`\n测试结果已保存到: ${TEST_RESULTS_FILE}`);
}

// 主测试函数
async function runTests() {
  try {
    log('# 用户关注功能测试');
    log(`测试时间: ${new Date().toISOString()}`);
    log(`API基础URL: ${API_BASE_URL}`);
    log(`测试用户: ${LOGIN_USER.email}`);
    log(`目标用户ID: ${TARGET_USER_ID}`);
    
    // 步骤1: 登录
    const loginSuccess = await login();
    if (!loginSuccess) {
      log('登录失败，测试终止');
      saveResults();
      process.exit(1);
    }
    
    // 步骤2: 检查初始关注状态
    const initialStatus = await checkFollowStatus();
    
    // 步骤3: 切换关注状态
    const newStatus = await toggleFollow();
    if (initialStatus !== null && newStatus !== null) {
      // 验证状态确实发生了改变
      if (initialStatus !== newStatus) {
        log('✓ 验证成功: 关注状态已正确切换');
      } else {
        log('✗ 验证失败: 关注状态未发生改变');
      }
    }
    
    // 步骤4: 再次检查关注状态
    await checkFollowStatus();
    
    // 步骤5: 获取关注统计
    await getFollowStats();
    
    // 步骤6: 获取关注列表
    await getFollowingList();
    
    // 步骤7: 批量检查关注状态
    await batchCheckFollowStatus();
    
    // 如果测试成功，恢复初始状态
    if (initialStatus !== null && newStatus !== null && initialStatus !== newStatus) {
      log('\n=== 恢复初始关注状态 ===');
      await toggleFollow();
      await checkFollowStatus();
    }
    
    log('\n=== 测试完成 ===');
    
    // 保存测试结果
    saveResults();
    
    // 判断测试是否全部通过
    const hasFailures = results.some(r => r.startsWith('✗'));
    process.exit(hasFailures ? 1 : 0);
    
  } catch (error) {
    log(`\n✗ 测试过程中发生错误: ${error.message}`);
    saveResults();
    process.exit(1);
  }
}

// 执行测试
runTests();